<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>出库</title>
<meta name="decorator" content="default" />
<link rel="stylesheet" type="text/css"
	href="${ctxStatic}/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
	href="${ctxStatic}/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css"
	href="${ctxStatic}/easyui/demo/demo.css">
<script type="text/javascript" src="${ctxStatic}/easyui/jquery.min.js"></script>
<script type="text/javascript"
	src="${ctxStatic}/easyui/jquery.easyui.min.js"></script>
	<link rel="stylesheet" type="text/css"
		href="${ctxStatic}/font-awesome-4.7.0/css/font-awesome.min.css">
	<style type="text/css">
		.butleft{
			float:left;
		}
		.butright{
			float:right;
		}
		.fa{
			font-size: 18px;
		}
	</style>
</head>
<body>
	<%-- <ul class="nav nav-tabs">
		<li class="active"><a href="${ctx}/erp/warehouse/storage">入库</a></li>
		<li><a href="${ctx}/erp/warehouse/outBound">出库</a></li>
	</ul> --%>
	<!--  入库基本信息 start -->
	出库编号*：<input class="easyui-textbox" id="code" data-options="prompt:'入库编号'" style="width:20%;height:32px" readOnly="readOnly" >
	
	<div style="margin:5px 0;"></div>
	<!--  入库基本信息 end -->
	<br /> 
	<!-- 物品详细 start -->
	<table id="datag" class="easyui-datagrid" title="记录清单" style="height:auto"
			data-options="
				iconCls: 'icon-edit',
				singleSelect: true,
				toolbar: '#tb',
				rownumbers:true,
				onClickCell: onClickCell
			">				<!-- ,onEndEdit: onEndEdit -->
			
		<thead>
			<tr>
				<th data-options="field:'goodsCode',width:100,editor:{  
								        type:'textbox',  
								        options:{  
								        	readonly:true,
								        	precision:0,
								            missingMessage:'数量必填!'  
								        }  
								    } ">物品编号</th>
				<th data-options="field:'mnemonicCode',width:100,editor:{  
								        type:'textbox',  
								        options:{  
								        	readonly:true,
								        	precision:0
								        }  
								    } ">助记码</th>
				<th data-options="field:'goodsName',width:500,editor:{  
								        type:'combogrid',  
								        options:{  
								        	precision:0,
								            required:true ,   
								            missingMessage:'物品必填!',
								            idField:'name',  // idField:'codes',  
		                                    textField:'name',     
		                                    multiple:false,//多选按钮  
		                                    pagination : false,//是否分页   
		                                    mode : 'remote',//远程连接方式  
		                                    fitColumns:true,//自动大小    
		                                    //queryParams:searchParam,//当请求远程数据时，发送的额外参数  
		                                    method:'get',//请求方式  
		                                    dataType:'json',  
		                                    panelWidth:800,
		                                    columns:[[     
												{field:'name',title:'名称',fitColumns:true},		
												{field:'code',title:'编码',fitColumns:true},   
												{field:'amount',title:'库存量',fitColumns:true},  
												{field:'type',title:'类型',fitColumns:true}  
		                                    ]], 
		                                    onSelect:function(recordidex,rowData){
		                                    	returnGCode(recordidex,rowData);
		                                    },
		                                    keyHandler:{ 
		                                    	 up: function(){},  
		                                         down: function(){},  
		                                         enter: function(){},
		                                         query:function(q){
		                                         	<%--if(q.length>=9){
								                   		q=q.trim();--%>
								                   		quickDimQuery(q);
								                   <%--	}--%>
		                                         }
		                                    }}}">物品名称</th>
				<th data-options="field:'goodsAmount',width:100,editor:{  
								        type:'numberbox',  
								        options:{  
								        	precision:0,
								            required:true ,   
								            missingMessage:'数量必填!'  
								        }  
								    }">物品数量</th>
				
				<%-- <th data-options="field:'repository',width:200,
						formatter:function(value,row){
							return row.repositoryName;
						},
						editor:{
							type:'combotree',
							options:{
								valueField:'id',
								textField:'text',
								method:'get',
								url:'${ctx}/erp/warehouse/queryRepository',
								required:true
							}
						}">仓库</th> --%>
				<!-- <th data-options="field:'repository',width:200,align:'left',editor:{type:'textbox'}">仓库</th> -->
				<th data-options="field:'remarks',width:150,align:'left',editor:{type:'textbox'}">备注</th>
			</tr>
		</thead>
	</table>

	<div id="tb" style="height:auto">
		<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" onclick="append()">追加</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="removeit()">移除</a>
		<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true" onclick="accept()">保存</a>
	</div>
	<!-- 物品详细 end -->
	<div style="margin-bottom: 10px;"></div>
	
	<!-- 人物 start -->
	执行人：<input class="easyui-combotree" data-options=""  style="width:200px;" id="executor" />
	操作人：<select class="easyui-combotree" data-options=""  style="width:200px;" id="operator" readOnly="readOnly" ></select>
	审核人：<select class="easyui-combotree" data-options=""  style="width:200px;" id="verifier"></select>
	<!-- 人物 end -->
	<!-- 订单详情 start -->
	<div id="dlg" class="easyui-dialog" title="订单" style="width:60%;height:auto;padding:10px"
			data-options="
				iconCls: 'icon-save'
			">
		<div style="margin-bottom:5px">
			<span>编号：</span><input  class='easyui-textbox' id="formcode" style='width:30%;height:22px' readonly="true" />
			<span >申请日期：</span> <input class='easyui-textbox' id="formapprovaldate"  style='width:40%;height:22px' readonly="true">
		</div >
		<div style="margin-bottom:5px">
			<span >审核人：</span> <input class='easyui-textbox' id="formverifier" style='width:20%;height:22px' readonly="true">
			<span >执行人：</span> <input class='easyui-textbox' id="formexecutor" style='width:20%;height:22px' readonly="true">
			<span >操作人：</span> <input class='easyui-textbox' id="formoperator" style='width:20%;height:22px' readonly="true">
		</div>
		<table id="gstb" title="物品详情"
			style="width: 100%; height: auto" data-options="
					rownumbers:true,
					singleSelect:true,
					autoRowHeight:false,
					pagination:true,
					pageSize:10">
			<thead>
				<tr>
					<th data-options="field:'gscode',width:100,align:'center'">物品编号</th>
					<th data-options="field:'gsname',width:200,align:'center'">物品名称</th>
					<th data-options="field:'gsamount',width:80,align:'center'">物品数量</th>
					<th data-options="field:'remarks',width:150,align:'center'">备注</th>
				</tr>
			</thead>
		</table>
	</div>
	<!-- 订单详情 end -->
	
	
	<div></div>
	
	<div style="padding:10px;" class="butleft">
		<a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="sub();">提交</a>
		<a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="temporarilySave();">暂时保存</a>
	</div>
	<div style="padding:10px 20px;" class="butright">
		<a href="#" class="start"><i class="fa fa-step-backward" aria-hidden="true"></i></a>
		<a href="#" class="left"><i class="fa fa-backward" aria-hidden="true"></i></a>
		<a href="#" class="right"><i class="fa fa-forward" aria-hidden="true"></i></a>
		<a href="#" class="end"><i class="fa fa-step-forward" aria-hidden="true"></i></a>
	</div>
	
	<!-- 提交 -->
	<script type="text/javascript">
		//4按钮start
		var indexPage=-1;	//当前页
		var sort='desc';	//排序类型
		var ordersType='0';	//订单类型
		var compare=null;
		//4按钮模块化
		var butModel={
				start:function(){
					$(".start").click(function(){
						indexPage=0;
						sort='asc'
						showDetails(indexPage,sort,ordersType);
					});
				},
				left:function(){
					$(".left").click(function(){
						if(compare==0 && sort=='asc'){
							indexPage=0;
						}
						if(sort=='desc'){
							indexPage+=1;
						}else{
							if(indexPage>=1){
								indexPage-=1;
							}else{
								indexPage=0;
							}
							
						}
						showDetails(indexPage,sort,ordersType);
					});
				},
				right:function(){
					$(".right").click(function(){
						if(compare==0 && sort=='desc'){
							indexPage=0;
						}
						if(sort=='asc'){
							indexPage+=1;
						}else{
							if(indexPage>=1){
								indexPage-=1;
							}else{
								indexPage=0;
							}
						}
						showDetails(indexPage,sort,ordersType);
					});
					
				},
				end:function(){
					$(".end").click(function(){
						indexPage=0;
						sort='desc'
						showDetails(indexPage,sort,ordersType);
					});
				}
		};
		butModel.start();
		butModel.left();
		butModel.right();
		butModel.end();
	
		function showDetails(){
			$.ajax({
			    url: '${ctx}/erp/warehouse/queryPutInOnlyOrders',         
			    data: {index:indexPage,sort:sort,type:ordersType},
			    dataType: "json",
			    type: "POST",          
			    success: function (data) {
			    	if(null!=data){
			    		indexPage=data.amount;
				    	compare=indexPage;
				    	$("#dlg").dialog({
				    		onOpen:function(){
				    			$("#formcode").textbox('setValue',data.code);//编号
								$("#formapprovaldate").textbox('setValue',data.approvalDate);//申请日期
								$("#formverifier").textbox('setValue',data.verifier);//审核人
								$("#formexecutor").textbox('setValue',data.executor);//执行人
								$("#formoperator").textbox('setValue',data.operator);//填表人
								
								$('#gstb').datagrid({
									data : getDialogData(data)
								}).datagrid({loadFilter:pagerFilter});
				    		}
				    	});
			    	}else{
			    		indexPage=indexPage-1;
			    	}
			    	
			    }
			});
		}
		function getDialogData(data){
			var initData = data;
			var rows = [];
			for(var i=0;i<initData.goods.length;i++){
				rows.push({
					gscode : initData.goods[i].code,
					gsname : initData.goods[i].name,
					gsamount : initData.goods[i].amount,
					remarks : initData.goods[i].remarks
					/* gsspecification : initData[rowindex].goods[i].specification */
				});
			} 
			return rows;
		}
		
		function pagerFilter(data) {
			if (typeof data.length == 'number'
					&& typeof data.splice == 'function') { // is array
				data = {
					total : data.length,
					rows : data
				}
			}
			var dg = $(this);
			var opts = dg.datagrid('options');
			var pager = dg.datagrid('getPager');
			pager.pagination({
				onSelectPage : function(pageNum, pageSize) {
					opts.pageNumber = pageNum;
					opts.pageSize = pageSize;
					pager.pagination('refresh', {
						pageNumber : pageNum,
						pageSize : pageSize
					});
					dg.datagrid('loadData', data);
				}
			});
			if (!data.originalRows) {
				data.originalRows = (data.rows);
			}
			var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
			var end = start + parseInt(opts.pageSize);
			data.rows = (data.originalRows.slice(start, end));
			return data;
		}
		//4按钮end
	
		//编辑表单 start
		var editIndex = undefined;
		function endEditing(){
			if (editIndex == undefined){return true}
			if ($('#datag').datagrid('validateRow', editIndex)){
				$('#datag').datagrid('endEdit', editIndex);
				editIndex = undefined;
				return true;
			} else {
				return false;
			}
		}
		function onClickCell(index, field){
			if (editIndex != index){
				if (endEditing()){
					$('#datag').datagrid('selectRow', index)
							.datagrid('beginEdit', index);
					var ed = $('#datag').datagrid('getEditor', {index:index,field:field});
					if (ed){
						($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
					}
					editIndex = index;
				} else {
					setTimeout(function(){
						$('#datag').datagrid('selectRow', editIndex);
					},0);
				}
			}
		}
		/* function onEndEdit(index, row){
			var ed = $(this).datagrid('getEditor', {
				index: index,
				field: 'repository'
			});
			row.repositoryName = $(ed.target).combobox('getText');
		} */
		function append(){
			if (endEditing()){
				$('#datag').datagrid('appendRow',{status:'P'});
				editIndex = $('#datag').datagrid('getRows').length-1;
				$('#datag').datagrid('selectRow', editIndex)
						.datagrid('beginEdit', editIndex);
			}
		}
		function removeit(){
			if (editIndex == undefined){return}
			$.messager.confirm('提示信息' , '确认删除?' , function(r){  
            	if(r){  
            		$('#datag').datagrid('cancelEdit', editIndex)
					.datagrid('deleteRow', editIndex);
					editIndex = undefined;
                } else {  
                     return ;  
                } 
            });
		}
		function accept(){
			if (endEditing()){
				$('#datag').datagrid('acceptChanges');
			}
		}
		//编辑表单 end
		
		//组合网格模糊快速查询
		function quickDimQuery(q){
			var url = 'dimQueryGoods';
        	var row = $('#datag').datagrid('getSelected');  
            var rowIndex = $('#datag').datagrid('getRowIndex',row);//获取行号  
            var thisTarget = $('#datag').datagrid('getEditor', {'index':rowIndex,'field':'goodsName'}).target;
            var grid =thisTarget.combogrid('grid');
            if(q!=null&&""!=q){
            	$(grid).datagrid('options').url= url+"?key="+q;
            }else{
            	$(grid).datagrid('options').url= url;  
            }
            $(grid).datagrid('load');
            thisTarget.combogrid('setValue', q);
		}
		//选中物品栏自动填充物品编号
		function returnGCode(recordidex,rowData){
			var row = $('#datag').datagrid('getSelected');  
            var rowIndex = $('#datag').datagrid('getRowIndex',row);//获取行号  
            var thisTarget = $('#datag').datagrid('getEditor', {'index':rowIndex,'field':'goodsCode'});
            $(thisTarget.target).textbox('setValue', rowData.code);//设置值
            var mnemonicCode = $('#datag').datagrid('getEditor', {'index':rowIndex,'field':'mnemonicCode'});
            $(mnemonicCode.target).textbox('setValue', rowData.mnemonicCode);//设置值
		}
		
		
		var operator='';
		var verifier='';
		var executor='';
		var nameList=[];
		var _list ={};
		
		function getPar(){
			//时间
			var myDate = new Date();
			var month=myDate.getMonth()+1;
			var day=myDate.getDate();
			if(month>=1&&month<10){
				month="0"+month;
			}
			if(day>=1&&day<10){
				day="0"+day;
			}
			var time=(myDate.getMonth()+1)+"/"+myDate.getDate()+"/"+myDate.getFullYear()+" "+myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds();
			
			var code=$("#code").textbox('getValue');
			executor=$("#executor").combotree('getValue');
			operator=$("#operator").combotree('getValue');
			verifier=$("#verifier").combotree('getValue');
			
			var amountList=[];
			var remarksList=[];
			var rows = $('#datag').datagrid('getRows');
			for (var i = 0; i < rows.length; i++) {
				nameList.push(rows[i].goodsCode);
				amountList.push(rows[i].goodsAmount);
				remarksList.push(rows[i].remarks);
			}
			_list={'nameList':nameList.toString(),'remarksList':remarksList.toString(),'amountList':amountList.toString(),'code':code,
					'executor':executor,'operator':operator,'verifier':verifier,'type':'0','time':time};
		}
		//提交
		function sub(){
			getPar();
			
			if(''==nameList){
				isParameterEmpty('缺少参数','物件内容为空!');
				return;
			}
			if(operator==''){
				isParameterEmpty('缺少参数','填表人（操作人）为空!');
				return;
			}
			if(executor==''){
				isParameterEmpty('缺少参数','执行人为空!');
				return;
			}
			if(verifier==''){
				isParameterEmpty('缺少参数','订单审核人为空!');
				return;
			}
			
			//验证库存数量是否充足
			var result='';
			var name='';
			$.ajax({
			    url: '${ctx}/erp/warehouse/isGoodsdEnough',         
			    data: _list,
			    dataType: "json",
			    type: "POST",     
			    async: false,
			    success: function (data) {
			        var size=data.length;
			        if(size>0){
			        	for(var i=0;i<size;i++){
			        		if(i==0){
			        			name=data[i].name
			        		}else{
			        			name=name+"-"+data[i].name;
			        		}
			        	}
			        	result='1';
			        }
			    }
			}); 
			if(result==1){
				$.messager.alert('警告', name+'库存数量不够', 'info');
				return;
			}
			//提交
			$.ajax({
			    url: '${ctx}/erp/warehouse/takeOutMerchandise',         
			    data: _list,
			    dataType: "json",
			    type: "POST",          
			    success: function (data) {
		        	$.messager.alert('出库完成','成功完成出库申请!','info',function(){
		        		window.location.href="${ctx}/erp/warehouse/takeOut"; 
			    	});
			    },
				error: function(){
			    	$.messager.alert('出库错误','出库出现未知错误!','error',function(){
			    		window.location.href="${ctx}/erp/warehouse/takeOut"; 
			    	});
			    }
			});  
		}
		
		//暂时保存
		function temporarilySave(){
			getPar();
			$.ajax({
			    url: '${ctx}/erp/warehouse/inTemporarilySave',         
			    data: _list,
			    dataType: "json",
			    type: "POST",          
			    success: function (data) {
			    	if(data==1){
			    		$.messager.alert('完成','保存成功!','info',function(){
			        		window.location.href="${ctx}/erp/warehouse/takeOut"; 
				    	});
			    	}else{
			    		$.messager.alert('错误','保存出错!','error',function(){
				    		window.location.href="${ctx}/erp/warehouse/takeOut"; 
				    	});
			    	}
			    	
			    },
			    error: function(){
			    	$.messager.alert('错误','保存出错!','error',function(){
			    		window.location.href="${ctx}/erp/warehouse/takeOut"; 
			    	});
			    }
			});
			
		}
		
	</script>

	<!-- 人物 -->
	<script type="text/javascript">
	function getDialogDatainit(data){
		var initData = data;
		var rows = [];
		for(var i=0;i<initData.goods.length;i++){
			rows.push({
				goodsCode : initData.goods[i].code,
				goodsName : initData.goods[i].name,
				goodsAmount : initData.goods[i].amount,
				remarks : initData.goods[i].remarks
				/* gsspecification : initData[rowindex].goods[i].specification */
			});
		} 
		return rows;
	}
	
		$(function(){
			$('#dlg').dialog('close');
			var myDate = new Date();
			var month=myDate.getMonth()+1;
			var day=myDate.getDate();
			if(month>=1&&month<10){
				month="0"+month;
			}
			if(day>=1&&day<10){
				day="0"+day;
			}
			
			
//			查询针对当前用户是否存在未完成的订单
			var unfinished=null;
			$.ajax({
			    url: '${ctx}/erp/warehouse/queryPersonalUnfinishedOrders',         
			    data: {type:"0"},
			    dataType: "json",
			    type: "POST",
			    async:false,
			    success: function (data) {
			    	unfinished=data;
			    }
			}); 
			var times='';
			$.ajax({
			    url: '${ctx}/erp/warehouse/ordersTimes',         
			    data: {"type":"ob"},
			    dataType: "json",
			    type: "POST",
			    async:false,
			    success: function (data) {
			    	times=data;
			    }
			}); 
			$("#code").textbox('setValue','ob'+myDate.getFullYear()+month+day+times);
			
			
			var data1='${WorkersData}';
			data1="["+data1+"]";
			data1 = eval("("+data1+")");
			$('#executor').combotree({
				data:data1,
				onSelect : function(node) {  
			        //返回树对象  
			        var tree = $(this).tree;  
			        //选中的节点是否为叶子节点,如果不是叶子节点,清除选中  
			        var isLeaf = tree('isLeaf', node.target);  
			        if (!isLeaf) {  
			            //清除选中  
			            $('#executor').combotree('clear');  
			        }  
			    }  
			});
			var data2='${Self}';
			data2="["+data2+"]";
			data2 = eval("("+data2+")");
			
			console.log('${WorkersData}');
			console.log(data2);
			$('#operator').combotree({
				data:data2,
			});
			$('#operator').combotree('setValue',data2[0].id);
			
			
			$('#verifier').combotree({
				data:data1,
				onSelect : function(node) {  
			        //返回树对象  
			        var tree = $(this).tree;  
			        //选中的节点是否为叶子节点,如果不是叶子节点,清除选中  
			        var isLeaf = tree('isLeaf', node.target);  
			        if (!isLeaf) {  
			            //清除选中  
			            $('#verifier').combotree('clear');  
			        }  
			    }  
			});
			
			//设置默认值
			if(null!=unfinished&&''!=unfinished){
				console.log(unfinished);
				$("#code").textbox('setValue',unfinished.code);
				$("#executor").combotree('setValue',unfinished.executor);
				$("#verifier").combotree('setValue',unfinished.verifier);
				$('#datag').datagrid({
					data : getDialogDatainit(unfinished)
				});
				
			}
			
		});
	</script>


	<!-- 物品 -->
	<script type="text/javascript">
		 function isParameterEmpty(title,mes){
			 $.messager.alert(title,mes,'info');
		 }
		
	</script>
</body>
</html>